﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data.Entity;
using System.Data;
using System.Reflection.Emit;
using System.Reflection;
using System.Data.Common;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;

namespace CollegeShop.Infrastructure.Entities
{
    public enum DatabaseType
    { 
        MsSql,
        MySql
    }
    public static class ContextExtensions
    {
        public static DataTable SqlQueryForDataTatable(this Database db,
               string sql,DatabaseType dbType,
               params System.Data.IDbDataParameter[] parameters)
        {

            IDbConnection conn = CreateDbConnection(dbType);
            conn.ConnectionString = db.Connection.ConnectionString;
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            IDbCommand cmd = conn.CreateCommand();
            cmd.Connection = conn;
            cmd.CommandText = sql;

            if (parameters.Length > 0)
            {
                foreach (var item in parameters)
                {
                    cmd.Parameters.Add(item);
                }
            }

            IDbDataAdapter adapter = CreateDbDataAdapter(cmd, dbType);// new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adapter.Fill(ds);
            if (ds != null && ds.Tables.Count > 0)
            {
                return ds.Tables[0];
            }
            return null;
        }

        private static IDbDataAdapter CreateDbDataAdapter(IDbCommand cmd, DatabaseType dbType)
        {
            switch (dbType) 
            {
                default:
                case DatabaseType.MySql:
                    return new MySqlDataAdapter((MySqlCommand)cmd);
                case DatabaseType.MsSql:
                    return new SqlDataAdapter((SqlCommand)cmd);
            }
        }

        private static IDbConnection CreateDbConnection(DatabaseType dbType)
        {
            switch (dbType)
            { 
                default:
                case DatabaseType.MySql:
                    return new MySqlConnection();
                case DatabaseType.MsSql:
                    return new SqlConnection();
            }
        }

        public static UpdateContext<T> Update<T>(this Context ctx) where T : class
        {
            return new UpdateContext<T>(ctx);
        }

        public static DeleteContext<T> Delete<T>(this Context ctx) where T : class
        {
            return new DeleteContext<T>(ctx);
        }

        public static DataTable ExcuteSQL(this Context ctx, string sqlCommand, params System.Data.IDbDataParameter[] parameters)
        {
            return ctx.Database.SqlQueryForDataTatable(sqlCommand, DatabaseType.MySql, parameters);
        }
    }
}
